package com.jl.card.file;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import com.jl.util.HexUtil;
import com.jl.util.StrUtil;

public final class CardFilePath {

	private final static String FILE_ROOT = "3F00";

	private final static String FILE_SEP = "/";
	private final List<String> path = new ArrayList<String>();

	public CardFilePath(String path) {
		path = StrUtil.replaceSpace(path);
		String[] pathArray = path.split(FILE_SEP);
		for (String p : pathArray) {
			p = HexUtil.compact(p.toUpperCase());
			if (!p.equals("")) {
				this.path.add(p);
			}
		}
		if (!this.path.get(0).equals(FILE_ROOT)) {
			this.path.add(0, FILE_ROOT);
		}
	}

	public CardFilePath(short[] path) {
		for (short p : path) {
			String str = HexUtil.compact(HexUtil.toHex(p & 0xFFFF, 2));
			this.path.add(str);
		}
	}

	public Iterator<String> iterator() {
		return new FileIteretor();
	}

	private class FileIteretor implements Iterator<String> {

		private int index = 0;

		public FileIteretor() {
		}

		@Override
		public boolean hasNext() {
			return index < path.size();
		}

		@Override
		public String next() {
			return path.get(index++);
		}

		@Override
		public void remove() {
			throw new UnsupportedOperationException("can,t remove it");
		}
	}

	public short getID(int leval) {
		return (short) (Integer.parseInt(path.get(leval), 16) & 0xFFFF);
	}
	
	public int getDeep(){
		return path.size();
	}

	public boolean isOnlyMF() {
		return path.size() == 1;
	}

	@Override
	public String toString() {
		StringBuilder sb = new StringBuilder();
		for (String str : path) {
			sb.append(FILE_SEP);
			sb.append(str);
		}
		sb.append(FILE_SEP);
		return sb.toString();
	}

}
